using System;
using System.Collections.ObjectModel;
using Avalonia.Controls;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.Extensions.Logging;
using SchoolApp_Material.Models;
using SchoolApp_Material.Msgs;

namespace SchoolApp_Material.ViewModels;

public class FormMgrViewModel : ViewModelBase
{
    private ILogger<FormMgrViewModel> _logger;
    private IFreeSql _freeSql;

    public FormMgrViewModel()
    {
        if (!Design.IsDesignMode) return;
    }

    public FormMgrViewModel(ILogger<FormMgrViewModel> logger, IFreeSql freeSql)
    {
        if(Design.IsDesignMode) return;
        _logger = logger;
        _freeSql = freeSql;
        Pagination = new PaginationViewModel(ExecuteQueryCmd);
    }

    #region 属性

    private string _year;

    public string Year
    {
        get => _year;
        set => SetProperty(ref _year, value);
    }

    private string _code;

    public string Code
    {
        get => _code;
        set => SetProperty(ref _code, value);
    }

    private ObservableCollection<FormViewModel> _formList = [];

    public ObservableCollection<FormViewModel> FormList
    {
        get => _formList;
        set => SetProperty(ref _formList, value);
    }

    private PaginationViewModel _pagination;

    public PaginationViewModel Pagination
    {
        get => _pagination;
        set => SetProperty(ref _pagination, value);
    }

    #endregion

    #region 命令

    #region 查询

    private RelayCommand _queryCmd;

    public RelayCommand QueryCmd =>
        _queryCmd ??= new RelayCommand(ExecuteQueryCmd, CanExecuteQueryCmd);

    private void ExecuteQueryCmd()
    {
        FormList.Clear();
        var iQuery = _freeSql.Select<Form>().Where(f => !f.IsDeleted);
        if (!string.IsNullOrEmpty(Year))
        {
            var year = int.Parse(Year);
            iQuery = iQuery.Where(f => f.Year == year);
        }

        if (!string.IsNullOrEmpty(Code))
            iQuery = iQuery.Where(f => f.Code == Code);
        Pagination.RowCount = iQuery.Count();
        Pagination.PageCount = (int)Math.Ceiling((double)Pagination.RowCount / Pagination.PageSize);
        iQuery = iQuery.OrderByDescending(f => f.Id).Skip((Pagination.PageNo - 1) * Pagination.PageSize).Take(Pagination.PageSize);
        var sql = iQuery.ToSql();
        var forms = iQuery.ToList();
        if (forms.Count > 0)
        {
            foreach (var form in forms)
            {
                FormList.Add(new FormViewModel()
                {
                    Id = form.Id,
                    Year = form.Year.ToString(),
                    Code = form.Code,
                    TeacherCode = form.TeacherCode,
                    TeacherName = form.TeacherName,
                    CreateOperatorCode = form.CreateOperatorCode,
                    CreateOperatorName = form.CreateOperatorName,
                    CreateTime = form.CreateTime,
                    EditAction = Edit,
                    DelAction = Delete
                });
            }
        }
    }

    private bool CanExecuteQueryCmd()
    {
        return true;
    }

    #endregion

    #region 新增

    private RelayCommand _addCmd;

    public RelayCommand AddCmd =>
        _addCmd ??= new RelayCommand(ExecuteAddCmd);

    private void ExecuteAddCmd()
    {
        WeakReferenceMessenger.Default.Send(new MsgBase<FormViewModel>() { Data = new FormViewModel() });
    }

    #endregion

    #endregion

    #region 方法

    private void Edit(FormViewModel form)
    {
        WeakReferenceMessenger.Default.Send(new MsgBase<FormViewModel>() { Data = form });
    }

    private void Delete(FormViewModel form)
    {
        form.CanDel = false;
        WeakReferenceMessenger.Default.Send(new FormDelMsg() { Form = form, ConfirmAction = () =>
        {
            var rowCount = _freeSql.Update<Form>()
                .Set(f => f.IsDeleted, true)
                .Set(f => f.UpdateTime, DateTime.Now)
                .Set(f => f.UpdateOperatorCode, Common.LoginOperator.Code)
                .Set(f => f.UpdateOperatorName, Common.LoginOperator.Name)
                .Where(f => f.Id == form.Id).ExecuteAffrows();
            _logger.LogInformation($"删除Form数据{rowCount}行");
            FormList.Remove(form);
        },CancelAction = () =>
        {
            form.CanDel = true;
        }});
    }

    #endregion
}